package com.netease.nie.base.data;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 
 * @author KingsHunter
 * @createDate June 15th,2016
 * 
 */
@Aspect
@Component
public class DataSourceAspect {
	
	@Pointcut("execution(* com.netease.nie.dao.*.*(..))")
	public void declareDynamicDataSourceExpression() {
	}
	
	@Before("declareDynamicDataSourceExpression()")
	public void setDataSourceKey(JoinPoint point) {
		Signature signature = point.getSignature();
		String methodName = signature.getName();
		if (DBReadMethodType.isReadType(methodName)) {
			DynamicDataSourceContextHolder.setDatabaseType(DBOperType.READ);
		} else {
			DynamicDataSourceContextHolder.setDatabaseType(DBOperType.READ_AND_WRITE);
		}	
	}
	
	@After("declareDynamicDataSourceExpression()")
	public void restoreDataSourceKey(JoinPoint point) {
		DynamicDataSourceContextHolder.clearDatabaseType();
	}
	
}
